// Copyright 2009 sbva project
//
// This file is part of sbva,
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.googlecode.sbva.example.businessobjects.validator;

import com.googlecode.sbva.example.businessobjects.ZipCode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
public class ZipCodeBaseValidator {

   private static Pattern zipPattern = Pattern.compile("[0-9]{5}");
   private static Pattern plus4Pattern = Pattern.compile("[0-9]{4}");
   private static Pattern zipAndPlus4Pattern = Pattern.compile("[0-9]{5}-[0-9]{4}");
 
   public static boolean isValid(String zip, String plus4) {

      Matcher plus4Matcher = plus4Pattern.matcher(plus4);
      boolean isPlus4 = plus4Matcher.matches();

      Matcher zipMatcher = zipPattern.matcher(zip);
      boolean isZip = zipMatcher.matches();

      if (isZip && plus4 == null
              || isZip && isPlus4) {

         return true;

      } else {

         return false;
      }


   }

   /**
    * Valid is XXXXX or XXXXX-XXXX
    *
    * where X is [0-9]
    *
    * @param zipAndPlus4
    * @return
    */
   public static boolean isValid(String zipAndPlus4) {

      Matcher zipAndPlus4Matcher = zipAndPlus4Pattern.matcher(zipAndPlus4);
      boolean isZipAndPlus4 = zipAndPlus4Matcher.matches();

      boolean isZip = false;

      if (!isZipAndPlus4) {

         Matcher zipMatcher = zipPattern.matcher(zipAndPlus4);
         isZip = zipMatcher.matches();

      }

      if (isZip || isZipAndPlus4) {

         return true;

      } else {

         return false;
      }

   }

   public static boolean isValid(ZipCode zipCode) {

      return isValid(zipCode.getZip(), zipCode.getPlus4());

   }
}
